package com.wxsong.authplatform.authweb.report;

import com.google.common.collect.Maps;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.j2ee.servlets.ImageServlet;
import org.apache.commons.lang3.time.DateFormatUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class IReportBuild {

    public static void buildReport() throws JRException, ParseException {
        //构建集合数据源
        List list = IReportData.buildData();
        JRDataSource jrDataSource = new JRBeanCollectionDataSource(list);
        Map<String, Object> params = Maps.newHashMap();
        params.put("exportTime", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        params.put("exportPersonName", "系统管理员");
        //构建报表File
        File reportFile = new File("F:\\MyWorkSpace\\authweb\\authweb\\template\\test1.jasper");
        JasperPrint jasperPrint = JasperFillManager.fillReport(reportFile.getPath(), params, jrDataSource);
        String fullPath = "F:\\MyWorkSpace\\authweb\\authweb\\template\\pdfreport\\out.pdf";
        JRPdfExporter pdfExporter = new JRPdfExporter();
        pdfExporter.setParameter(JRExporterParameter.JASPER_PRINT,jasperPrint);
        pdfExporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, fullPath);
        pdfExporter.exportReport();
    }

    public static void exportReport(HttpServletRequest request, HttpServletResponse response) throws JRException, ParseException, IOException {
        //构建集合数据源
        List list = IReportData.buildData();
        JRDataSource jrDataSource = new JRBeanCollectionDataSource(list);
        Map<String, Object> params = Maps.newHashMap();
        params.put("exportTime", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        params.put("exportPersonName", "系统管理员");
        //构建报表File
        File reportFile = new File("F:\\MyWorkSpace\\authweb\\authweb\\template\\test1.jasper");
        JasperPrint jasperPrint = JasperFillManager.fillReport(reportFile.getPath(), params, jrDataSource);
//        String fullPath = "F:\\MyWorkSpace\\authweb\\authweb\\template\\pdfreport\\out.pdf";
        JRPdfExporter pdfExporter = new JRPdfExporter();
        OutputStream out = response.getOutputStream();
        pdfExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
        pdfExporter.setParameter(JRExporterParameter.JASPER_PRINT,jasperPrint);
        pdfExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
        pdfExporter.exportReport();
        request.getSession().setAttribute(
                ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE,
                jasperPrint);
        out.flush();
    }

}
